import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimConversationListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimGroupListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimSDKListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/callbacks.dart';
import 'package:tencent_cloud_chat_sdk/enum/friend_type_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/group_add_opt_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/history_msg_get_type_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/log_level_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_priority_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/offlinePushInfo.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_callback.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_application_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_check_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_info_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_search_param.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message_receipt.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_msg_create_info_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_status.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_sdk/native_im/adapter/tim_friendship_manager.dart';
import 'package:tencent_cloud_chat_sdk/native_im/adapter/tim_manager.dart';
import 'package:tencent_cloud_chat_sdk/native_im/adapter/tim_message_manager.dart';
import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk_platform_interface.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';




class ImManager {
  static final ImManager _instance = ImManager._internal();

  factory ImManager() => _instance;

  ImManager._internal();

  V2TimConversationListener? _conversationListener;
  bool _conversationListenerAdded = false;
  V2TimAdvancedMsgListener? _messageListener;
  bool _messageListenerAdded = false;
  /// 初始化
  Future<void> init() async {
 bool isProduction = bool.fromEnvironment('dart.vm.product');

  int sdkAppID;
    // 1. 从即时通信 IM 控制台获取应用 SDKAppID。
    if (isProduction) {
        print('生产环境111');
     sdkAppID = 1600077950;

    }else{
     sdkAppID = 1400773991;

    }
    sdkAppID = 1600077950;

    
    // 2. 添加 V2TimSDKListener 的事件监听器，sdkListener 是 V2TimSDKListener 的实现类
    V2TimSDKListener sdkListener = V2TimSDKListener(
      onConnectFailed: (int code, String error) {
        // 连接失败的回调函数
        // code 错误码
        // error 错误信息
      },
      onConnectSuccess: () {
        // SDK 已经成功连接到腾讯云服务器
      },
      onConnecting: () {
        // SDK 正在连接到腾讯云服务器
      },
      onKickedOffline: () {
        // 当前用户被踢下线，此时可以 UI 提示用户，并再次调用 V2TIMManager 的 login() 函数重新登录。
      },
      onSelfInfoUpdated: (V2TimUserFullInfo info) {
        // 登录用户的资料发生了更新
        // info登录用户的资料
      },
      onUserSigExpired: () {
        // 在线时票据过期：此时您需要生成新的 userSig 并再次调用 V2TIMManager 的 login() 函数重新登录。
      },
      onUserStatusChanged: (List<V2TimUserStatus> userStatusList) {
        //用户状态变更通知
        //userStatusList 用户状态变化的用户列表
        //收到通知的情况：订阅过的用户发生了状态变更（包括在线状态和自定义状态），会触发该回调
        //在 IM 控制台打开了好友状态通知开关，即使未主动订阅，当好友状态发生变更时，也会触发该回调
        //同一个账号多设备登录，当其中一台设备修改了自定义状态，所有设备都会收到该回调
      },
    );
    // 3.初始化SDK
    final result = await TencentImSDKPlugin.v2TIMManager.initSDK(
      sdkAppID: sdkAppID, // SDKAppID
      loglevel: LogLevelEnum.V2TIM_LOG_ALL, // 日志登记等级
      listener: sdkListener, // 事件监听器
    );
    debugPrint('=> IM初始化: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      //初始化成功
    }
  }

  /// 登录
  Future<bool> login(
    String userSig,
    String userId,
    String nickname, {
    String? faceUrl,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .login(userID: userId, userSig: userSig);
    debugPrint('=> IM登录: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      // 登录成功逻辑
      setSelfInfo(nickname: nickname, faceUrl: faceUrl);
      return Future.value(true);
    }
    return Future.value(false);
  }

  /// 登出
  Future<void> logout() async {
    final result = await TencentImSDKPlugin.v2TIMManager.logout();
    debugPrint('=> IM登出: ${result.code}, ${result.desc}');
    if (result.code == 0) {}
  }

  /// 获取好友列表
  Future<List<V2TimUserFullInfo>> getFriendList() async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendList();
    debugPrint('=> 获取好友列表: ${result.code}, ${result.desc}');
    if (result.code == 0 && (result.data?.isNotEmpty ?? false)) {
      final data = result.data?.map((item) => item.userProfile!).toList() ?? [];
      return Future.value(data);
    }
    return Future.value([]);
  }

  
  Future<V2TimValueCallback<V2TimFriendApplicationResult>>
    getFriendApplicationList() async {
  if (kIsWeb) {
    return TencentCloudChatSdkPlatform.instance.getFriendApplicationList();
  }

  return TIMFriendshipManager.instance.getFriendApplicationList();
}

 
Future<V2TimValueCallback<List<V2TimFriendCheckResult>>> checkFriend({
  required List<String> userIDList,
  required FriendTypeEnum checkType,
}) async {
  if (kIsWeb) {
    return TencentCloudChatSdkPlatform.instance.checkFriend(
      userIDList: userIDList,
      checkType: checkType.index,
    );
  }

  return TIMFriendshipManager.instance.checkFriend(
    userIDList: userIDList,
    checkType: checkType,
  );
}


  /// 添加好友
  Future<bool> addFriend({
    required String userId,
    String? remark,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .addFriend(
            userID: userId,
            remark: remark,
            addWording: "",
            addType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH);
    debugPrint('=> 添加好友: ${result.code}, ${result.desc}');
    return Future.value(result.code == 0);
  }

  // V2TIM_FRIEND_TYPE_SINGLE

  /// 删除好友
  Future<bool> deleteFriend({
    required String userId,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .deleteFromFriendList(
            deleteType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH,
            userIDList: [userId]);
    debugPrint('=> 删除好友: ${result.code}, ${result.desc}');
    return Future.value(result.code == 0);
  }
 
 
Future<V2TimCallback> markC2CMessageAsRead({
  required String userID,
}) async {
  if (kIsWeb) {
    return TencentCloudChatSdkPlatform.instance.markC2CMessageAsRead(userID: userID);
  }

  return TIMMessageManager.instance.markC2CMessageAsRead(userID: userID);
}

 

  Future<List<V2TimUserFullInfo>> getUsersInfo({

    
    required List<String> userIDList
  }) async {

    final result = await TencentImSDKPlugin.v2TIMManager.getUsersInfo(userIDList: userIDList);
    debugPrint('=> 获取好友列表: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      return Future.value(result.data);
    }
    return Future.value([]);
  }

 


  /// 获取好友信息
  Future<V2TimFriendInfoResult?> getFriendsInfo({
    required String userId,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendsInfo(userIDList: [userId]);
    debugPrint('=> 获取好友信息: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      final data = result.data?.first;
      return Future.value(data);
    }
    return Future.value(null);
  }

  /// 设置好友信息
  Future<V2TimCallback> setFriendInfo({
    required String userId,
    String? friendRemark,
    Map<String, String>? friendCustomInfo,
  }) async {
    return TencentImSDKPlugin.v2TIMManager.getFriendshipManager().setFriendInfo(
        userID: userId,
        friendRemark: friendRemark,
        friendCustomInfo: friendCustomInfo);
  }

  /// 设置个人信息
  Future<V2TimCallback> setSelfInfo({
    required String nickname,
    String? faceUrl,
  }) {
    return TencentImSDKPlugin.v2TIMManager.setSelfInfo(
        userFullInfo: V2TimUserFullInfo(
      nickName: nickname,
      role: 0,
      faceUrl: faceUrl,
    ));
  }

  /// 获取会话列表
  Future<List<V2TimConversation>> getConversationList({
    required String nextSeq,
    required int count,
  }) async {
    
  final result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversationList(nextSeq: nextSeq, count: count);


    
    debugPrint('=> 获取会话列表: $result, ${result.desc}');
    debugPrint(jsonEncode(result));

      if(result.code==6014){
        Get.offNamed('/login/login_type');
      }
    if (result.code == 0) {
      return Future.value(result.data?.conversationList);
    }else{
      
    }
    return Future.value([]);
  }

  /// 获取会话详情
  Future<V2TimConversation?> getConversationDetails({
    required String conversationId,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: conversationId);
    debugPrint('=> 获取会话详情: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      return Future.value(result.data);
    }
    return Future.value(null);
  }

  /// 获取会话未读总数
  Future<int?> getTotalUnreadMessageCount() async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getTotalUnreadMessageCount();
    debugPrint('=> 获取会话未读总数: ${result.code}, ${result.desc}');
    if (result.code == 0) {
      return Future.value(result.data);
    }
    return Future.value(null);
  }

  /// 添加会话监听器
  Future<void> addConversationListener({
    required VoidCallback onConversationUpdated,
    required VoidCallback onTotalUnreadMessageCountUpdated,
  }) async {
    if (_conversationListenerAdded) return;

    _conversationListener = V2TimConversationListener(
      onNewConversation: (conversationList) => onConversationUpdated(),
      onConversationChanged: (conversationList) => onConversationUpdated(),
      onTotalUnreadMessageCountChanged: (totalUnreadCount) =>
          onTotalUnreadMessageCountUpdated(),
    );

    try {
      await TencentImSDKPlugin.v2TIMManager
          .getConversationManager()
          .addConversationListener(listener: _conversationListener!);
      _conversationListenerAdded = true;
    } catch (e) {
      debugPrint('添加会话监听器失败: $e');
      _conversationListener = null;
    }
  }

  /// 移除会话监听器
  Future<void> removeConversationListener() async {
    if (!_conversationListenerAdded || _conversationListener == null) return;

    try {
      await TencentImSDKPlugin.v2TIMManager
          .getConversationManager()
          .removeConversationListener(listener: _conversationListener!);
      _conversationListener = null;
      _conversationListenerAdded = false;
    } catch (e) {
      debugPrint('移除会话监听器失败: $e');
    }
  }

  /// 删除会话
  Future<bool> deleteConversation({
    required String conversationId,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .deleteConversation(conversationID: conversationId);
    debugPrint('=> 删除会话: ${result.code}, ${result.desc}');
    return Future.value(result.code == 0);
  }

// Future<V2TimCallback> markC2CMessageAsRead({
//   required String userID,
// }) async {
//   if (kIsWeb) {
//     return TencentCloudChatSdkPlatform.instance.markC2CMessageAsRead(userID: userID);
//   }

//   return V2TIMConversationManager.cleanConversationUnreadMessageCount(userID: userID);
// }

Future<V2TimValueCallback<int>> getLoginStatus() async {
  if (kIsWeb) {
    return TencentCloudChatSdkPlatform.instance.getLoginStatus();
  }

  int status = TIMManager.instance.getLoginStatus();
  return V2TimValueCallback<int>.fromObject(status);
}


  /// 清理指定单聊会话的未读数
  Future<bool> cleanConversationUnreadMessageCount({
    required String conversationId,
  }) async {
    final result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .cleanConversationUnreadMessageCount(
          conversationID: conversationId,
          cleanTimestamp: 0,
          cleanSequence: 0,
        );
    debugPrint('=> 清理指定单聊会话的未读数: ${result.code}, ${result.desc}');
    return Future.value(result.code == 0);
  }

  /// 获取历史消息
  Future<List<V2TimMessage>> getHistoryMessageList({
    String userId = '',
    String groupId = '',
  }) async {
    // 拉取单聊历史消息
    // 首次拉取，lastMsgID 设置为 null
    // 再次拉取时，lastMsgID 可以使用返回的消息列表中的最后一条消息的id
    V2TimValueCallback<List<V2TimMessage>> getHistoryMessageListRes =
        await TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .getHistoryMessageList(
      // 拉取消息的位置及方向
      getType: HistoryMsgGetTypeEnum.V2TIM_GET_LOCAL_OLDER_MSG,
      // 用户id 拉取单聊消息，需要指定对方的 userID，此时 groupID 传空即可。
      userID: userId,
      // 群组id 拉取群聊消息，需要指定群聊的 groupID，此时 userID 传空即可。
      groupID: groupId,
      // 拉取数据数量
      count: 100,
      // 拉取起始消息id
      // 仅能在群聊中使用该字段。
      // 设置 lastMsgSeq 作为拉取的起点，返回的消息列表中包含这条消息。
      // 如果同时指定了 lastMsg 和 lastMsgSeq，SDK 优先使用 lastMsg。
      // 如果均未指定 lastMsg 和 lastMsgSeq，拉取的起点取决于是否设置 getTimeBegin。设置了，则使用设置的范围作为起点；未设置，则使用最新消息作为起点。
      lastMsgID: null,
      lastMsgSeq: -1,
      messageTypeList: [], // 用于过滤历史信息属性，若为空则拉取所有属性信息。
    );
    debugPrint(
        '=> 获取历史消息: ${getHistoryMessageListRes.code}, ${getHistoryMessageListRes.desc}');
    if (getHistoryMessageListRes.code == 0) {
      //获取成功
      getHistoryMessageListRes.data
          ?.sort((a, b) => (a.timestamp ?? 0).compareTo((b.timestamp ?? 0)));
      return Future.value(getHistoryMessageListRes.data);
    }
    return Future.value([]);
  }

  /// 创建群聊
  Future<String?> createGroup({
    required String groupId,
    required String groupName,
  }) async {
    final result =
        await TencentImSDKPlugin.v2TIMManager.getGroupManager().createGroup(
      groupID: groupId,
      // 群类型 临时会议群（Meeting） 直播群（AVChatRoom）
      groupType: "Meeting",
      // 群名称，不能为 null。
      groupName: groupName,
      // 群公告
      notification: "",
      // 群介绍
      introduction: "",
      // 群头像Url
      faceUrl: "",
      // 是否全体禁言
      isAllMuted: false,
      // 是否支持话题
      isSupportTopic: false,
      // 添加群设置
      addOpt: GroupAddOptTypeEnum.V2TIM_GROUP_ADD_ANY,
      // 初始成员列表
      memberList: [],
    );
    debugPrint('=> 创建群聊: ${result.code}, ${result.desc}, ${result.data}');
    if (result.code == 0) {
      // 创建成功
      return result.data; // 创建的群号
    } else if (result.code == 10025 || result.code == 10021) {
      return groupId;
    }
    return null;
  }

  /// 加入群聊
  Future<void> joinGroup(
    String groupId,
    String nickname,
  ) async {
    V2TimCallback joinGroupRes = await TencentImSDKPlugin.v2TIMManager
        .joinGroup(groupID: groupId, message: "hello", groupType: "Meeting");
    debugPrint('=> 加入群聊: ${joinGroupRes.code}, ${joinGroupRes.desc}');
    if (joinGroupRes.code != 0 && joinGroupRes.code != 10013) {
      debugPrint('网络异常，请重试-2(code:${joinGroupRes.code})');
    }

    // 监听加入群组事件
    TencentImSDKPlugin.v2TIMManager.addGroupListener(
      listener: V2TimGroupListener(
        onMemberEnter: ((groupID, memberList) {
          // 加入成功，获取加入群的人员信息
        }),
      ),
    );
  }




  /// 发送消息
  Future<bool> sendMessage({
    String userId = '',
    String groupId = '',
    required String text,
  }) async {
    // 创建文本消息
    V2TimValueCallback<V2TimMsgCreateInfoResult> createTextMessageRes =
        await TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .createTextMessage(
              text: text, // 文本信息
            );
    if (createTextMessageRes.code == 0) {
      // 文本信息创建成功
      String? id = createTextMessageRes.data?.id;
      // 发送文本消息
      // 在sendMessage时，若只填写receiver则发个人用户单聊消息
      //                 若只填写groupID则发群组消息
      //                 若填写了receiver与groupID则发群内的个人用户，消息在群聊中显示，只有指定receiver能看见
      V2TimValueCallback<V2TimMessage> sendMessageRes =
          await TencentImSDKPlugin.v2TIMManager.getMessageManager().sendMessage(
              id: id!,
              // 创建的messageid
              receiver: userId,
              // 接收人id
              groupID: groupId,
              // 接收群组id
              priority: MessagePriorityEnum.V2TIM_PRIORITY_DEFAULT,
              // 消息优先级
              onlineUserOnly: false,
              // 是否只有在线用户才能收到，如果设置为 true ，接收方历史消息拉取不到，常被用于实现“对方正在输入”或群组里的非重要提示等弱提示功能，该字段不支持 AVChatRoom。
              isExcludedFromUnreadCount: false,
              // 发送消息是否计入会话未读数
              isExcludedFromLastMessage: false,
              // 发送消息是否计入会话 lastMessage
              needReadReceipt: false,
              // 消息是否需要已读回执（只有 Group 消息有效，6.1 及以上版本支持，需要您购买旗舰版套餐）
              offlinePushInfo: OfflinePushInfo(),
              // 离线推送时携带的标题和内容
              cloudCustomData: "",
              // 消息云端数据，消息附带的额外的数据，存云端，消息的接收者可以访问到
              localCustomData:
                  "" // 消息本地数据，消息附带的额外的数据，存本地，消息的接收者不可以访问到，App 卸载后数据丢失
              );
      debugPrint('=> 发送消息: ${sendMessageRes.code}, ${sendMessageRes.desc}');
      return Future.value(sendMessageRes.code == 0);
    }
    return Future.value(false);
  }

  /// 添加消息监听器
  Future<void> addMessageListener({
    required OnRecvNewMessageCallback onCallback,
  }) async {
    if (_messageListenerAdded) return;

    _messageListener = V2TimAdvancedMsgListener(
      onRecvC2CReadReceipt: (List<V2TimMessageReceipt> receiptList) {
        //单聊已读回调
      },
      onRecvMessageModified: (V2TimMessage message) {
        // msg 为被修改之后的消息对象
      },
      onRecvMessageReadReceipts: (List<V2TimMessageReceipt> receiptList) {
        //群聊已读回调
        for (var element in receiptList) {
          element.groupID; // 群id
          element.msgID; // 已读回执消息 ID
          element.readCount; // 群消息最新已读数
          element.unreadCount; // 群消息最新未读数
          element.userID; //  C2C 消息对方 ID
        }
      },
      onRecvMessageRevoked: (String messageId) {
        // 在本地维护的消息中处理被对方撤回的消息
      },
      onRecvNewMessage: (V2TimMessage message) async {
        debugPrint('消息监听: ${message.elemType}');
        onCallback(message);
        // 处理文本消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
          String? text = message.textElem?.text;
          debugPrint('接收消息: $text');
        }
        // 使用自定义消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
          message.customElem?.data;
          message.customElem?.desc;
          message.customElem?.extension;
        }
        // 使用图片消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
          message.imageElem
              ?.path; // 图片上传时的路径，消息发送者才会有这个字段，消息发送者可用这个字段将图片预先上屏，优化上屏体验。
          message.imageElem?.imageList?.forEach((element) {
            // 遍历大图、原图、缩略图
            // 解析图片属性
            element?.height;
            element?.localUrl;
            element?.size;
            element?.type; // 大图 缩略图 原图
            element?.url;
            element?.uuid;
            element?.width;
          });
        }
        // 处理视频消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_VIDEO) {
          // 解析视频消息属性，封面、播放地址、宽高、大小等。
          message.videoElem?.UUID;
          message.videoElem?.duration;
          message.videoElem?.localSnapshotUrl;
          message.videoElem?.localVideoUrl;
          message.videoElem?.snapshotHeight;
          message.videoElem?.snapshotPath;
          // ...
        }
        // 处理音频消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_SOUND) {
          // 解析语音消息 播放地址，本地地址，大小，时长等。
          message.soundElem?.UUID;
          message.soundElem?.dataSize;
          message.soundElem?.duration;
          message.soundElem?.localUrl;
          message.soundElem?.url;
          // ...
        }
        // 处理文件消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE) {
          // 解析文件消息 文件名、文件大小、url等
          message.fileElem?.UUID;
          message.fileElem?.fileName;
          message.fileElem?.fileSize;
          message.fileElem?.localUrl;
          message.fileElem?.path;
          message.fileElem?.url;
        }
        // 处理位置消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_LOCATION) {
          // 解析地理位置消息，经纬度、描述等
          message.locationElem?.desc;
          message.locationElem?.latitude;
          message.locationElem?.longitude;
        }
        // 处理表情消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE) {
          message.faceElem?.data;
          message.faceElem?.index;
        }
        // 处理群组tips文本消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS) {
          message.groupTipsElem?.groupID; // 所属群组
          message.groupTipsElem?.type; // 群Tips类型
          message.groupTipsElem?.opMember; // 操作人资料
          message.groupTipsElem?.memberList; // 被操作人资料
          message.groupTipsElem?.groupChangeInfoList; // 群信息变更详情
          message.groupTipsElem?.memberChangeInfoList; // 群成员变更信息
          message.groupTipsElem?.memberCount; // 当前群在线人数
        }
        // 处理合并消息消息
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_MERGER) {
          message.mergerElem?.abstractList;
          message.mergerElem?.isLayersOverLimit;
          message.mergerElem?.title;
          V2TimValueCallback<List<V2TimMessage>> download =
              await TencentImSDKPlugin.v2TIMManager
                  .getMessageManager()
                  .downloadMergerMessage(
                    msgID: message.msgID!,
                  );
          if (download.code == 0) {
            List<V2TimMessage>? messageList = download.data;
          }
        }
        if (message.textElem?.nextElem != null) {
          //通过第一个 Elem 对象的 nextElem 方法获取下一个 Elem 对象，如果下一个 Elem 对象存在，会返回 Elem 对象实例，如果不存在，会返回 null。
        }
      },
      onSendMessageProgress: (V2TimMessage message, int progress) {
        //文件上传进度回调
      },
    );

    try {
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .addAdvancedMsgListener(listener: _messageListener!);
    } catch (e) {
      debugPrint('添加消息监听器失败: $e');
    }
  }

  /// 移除消息监听器
  Future<void> removeMessageListener() async {
    if (!_messageListenerAdded || _messageListener == null) return;

    try {
      await TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .removeAdvancedMsgListener(listener: _messageListener!);
      _messageListener = null;
      _messageListenerAdded = false;
    } catch (e) {
      debugPrint('移除消息监听器失败: $e');
    }
  }
}
